package com.cuit.qx.controller;


import cn.hutool.http.HttpResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cuit.qx.bean.Warning;
import com.cuit.qx.entity.Checkout;
import com.cuit.qx.entity.CorrectForecast;
import com.cuit.qx.service.CheckoutService;
import com.cuit.qx.utils.HttpUtil;
import com.cuit.qx.utils.ReturnData;
import com.cuit.qx.utils.ReturnStateCode;
import com.sun.deploy.net.URLEncoder;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.servlet.ModelAndView;
import sun.rmi.runtime.Log;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lcj
 * @since 2021-11-25
 */
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/checkout")
public class CheckoutController {

    @Autowired
    private CheckoutService service;

    private static final Logger LOG = LoggerFactory.getLogger(CheckoutController.class);
    /**
     * @description:  type：0在线检验 1离线检验
      * @return:
     * @author: wjd
     * @time: 2021/11/25 11:08
     */
    @RequestMapping("/getCheckout")
    public ReturnData getCheckout(@RequestBody Map<String,String> map){

        LambdaQueryWrapper<Checkout> wrapper =new LambdaQueryWrapper();
        wrapper.eq(Checkout::getCheckoutType,map.get("type"));//0代表在线  1代表离线
        wrapper.ge(Checkout::getCheckoutDate,map.get("startTime")); //查询开始时间
        wrapper.le(Checkout::getCheckoutDate,map.get("endTime"));//查询结束时间
        wrapper.eq(Checkout::getCheckoutStaion,map.get("station"));//查询站点名称
        wrapper.eq(Checkout::getCheckoutTime,map.get("checoutTime"));//检验起报时间  08、20
        wrapper.eq(Checkout::getTimeliness,map.get("timeLiness"));//检验累计雨量 12h
        wrapper.eq(Checkout::getOrders,map.get("order"));//检验阈值 0.1、1.0
        wrapper.eq(Checkout::getCheckoutMethod,map.get("methond"));//检验方法
        //检验方法 0代表TS评分 1代表ETS 2代表空报 3代表漏报 4代表预报偏差 5代表命中率
        List<Checkout> list = service.list(wrapper);

        if (list.size()>0){
            return  new ReturnData(ReturnStateCode.SUCCEE.getCode(),ReturnStateCode.SUCCEE.getMsg(),list);
        }
        return  new ReturnData(ReturnStateCode.SUCCEEBUT.getCode(),ReturnStateCode.SUCCEEBUT.getMsg());
    }


    /**
     * @description: 下载检验数据
     * 检验方法： 0代表TS评分 1代表ETS 2代表空报 3代表漏报 4代表预报偏差 5代表命中率
     * 模式： 0代表 grepse  1 代表华南模式  2代表EC模式 3代表订正模式
     * @return:
     * @author: wjd
     * @time: 2021/11/25 14:49
     */
    @RequestMapping(value = "/exportXlChecoutData", method = RequestMethod.POST)
    public ModelAndView exportXlChecoutData(HttpServletResponse response, @RequestBody Map<String, String> map) throws UnsupportedEncodingException {

        LambdaQueryWrapper<Checkout> wrapper =new LambdaQueryWrapper();
        wrapper.eq(Checkout::getCheckoutType,map.get("type"));//0代表在线  1代表离线
        wrapper.ge(Checkout::getCheckoutDate,map.get("startTime")); //查询开始时间
        wrapper.le(Checkout::getCheckoutDate,map.get("endTime"));//查询结束时间
        wrapper.eq(Checkout::getCheckoutStaion,map.get("station"));//查询站点名称
        wrapper.eq(Checkout::getCheckoutTime,map.get("checoutTime"));//检验起报时间  08、20
        wrapper.eq(Checkout::getTimeliness,map.get("timeLiness"));//检验累计雨量 12h
        wrapper.eq(Checkout::getOrders,map.get("order"));//检验阈值 0.1、1.0
        wrapper.eq(Checkout::getCheckoutMethod,map.get("methond"));//检验方法

        List<Checkout> list = service.list(wrapper);
        ArrayList<Checkout> objects = new ArrayList<>(); //用来组装数据

        list.forEach(
                item->{
                    String pattern = pattern(item.getPattern());//模式
                    String s = checkouMethod(item.getCheckoutMethod());//检验方法
                    item.setPattern(pattern);
                    item.setCheckoutMethod(s);
                    objects.add(item);
                }
        );

        /**组装数据**/
        String fileName= map.get("station")+"站"+map.get("startTime")+"至"+map.get("endTime")+map.get("checoutTime")+"时"
                + checkouMethod(map.get("methond"))+"检验数据";
        String tile=map.get("station")+"逐"+map.get("timeLiness")+"降水预报"+checkouMethod(map.get("methond"))+"检验结果";

        String selectDate= map.get("startTime")+"至"+map.get("endTime");

        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment; filename = "+new String(fileName.getBytes(),"UTF-8"));

        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        // 导出文件名称
        try {
            mv.addObject(NormalExcelConstants.FILE_NAME,  new String(fileName.getBytes(),"UTF-8"));
        } catch (UnsupportedEncodingException e) {
            LOG.error("导出检验数据异常："+e);
            e.printStackTrace();
        }
        mv.addObject(NormalExcelConstants.CLASS, Checkout.class);
//        ExportParams exportParams = new ExportParams("站点检验数据", map.get("startTime")+"-"+map.get("endTime"), map.get("station"));
        ExportParams exportParams = new ExportParams(tile, "起报时间:"+selectDate, map.get("station"));
        exportParams.setImageBasePath("");
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, objects);
        return mv;
    }

    /**
     * @description:  访问接口获取检验数据，接口为另一家公司开发。
     * 参数：checkoutType 检验类型、 startnum 起报时刻、 startDate 查询开始时间 、endDate查询结束时间 、stationnum 站号
     *
     * @return:
     * @author: wjd
     * @time: 2022/1/4 9:41
     */
    @RequestMapping("/getOtherCheckout")
    public ReturnData getOtherCheckoutData(String checkoutType,String startnum,String startDate,String endDate,String  stationnum ){
        String offLine="";//离线检验文件目录
        String[] filePath={};
        String obtype="json";
        String micapsziplist="/data/home/lisiyan/data/wuzhou";  //在线实况目录
        String obfilepath="/data/home/lisiyan/data/wuzhou";//在线实况目录

        String micapsziplistL="/data/home/lisiyan/data/wuzhou";  //在线实况目录
        String obfilepathL="/data/home/lisiyan/data/wuzhou";//在线实况目录

        if (checkoutType.equals("0")){//在线检验
            //获取时间段
//            String substring = startDate.replace("-", "").substring(0,8);
//            String sbEndDate = endDate.replace("-", "").substring(0,8);
//            try { filePath = getFilePath(checkoutType,substring, sbEndDate);
//            } catch (ParseException e) {
//                LOG.error("组装文件目录异常",e);
//            }

            LOG.info("在线请求接口："+"http://58.217.204.132:8001/correctForecast/rain_eval?micapsziplist="+micapsziplist+
                    "&obfilepath="+obfilepath+"&startnum="+startnum+"&obtype="+obtype+"&starttime="+startDate+"&endtime="+endDate
                    +"&stationnum="+stationnum);

            String s = new HttpUtil().doGet("http://58.217.204.132:8001/correctForecast/rain_eval?micapsziplist="+micapsziplist+
                    "&obfilepath="+obfilepath+"&startnum="+startnum+"&obtype="+obtype+"&starttime="+startDate+"&endtime="+endDate
            +"&stationnum="+stationnum);

            return  new ReturnData(ReturnStateCode.SUCCEE.getCode(),ReturnStateCode.SUCCEE.getMsg(),s);
        }else{//离线检验
            //获取时间段
//            String substring = startDate.replace("-", "").substring(0,8);
//            String sbEndDate = endDate.replace("-", "").substring(0,8);
//            try { filePath = getFilePath(checkoutType,substring, sbEndDate);
//            } catch (ParseException e) {
//                LOG.error("组装文件目录异常",e);
//            }
            LOG.info("离线请求接口："+"http://58.217.204.132:8001/correctForecast/rain_eval?micapsziplist="+micapsziplist+
                    "&obfilepath="+obfilepath+"&startnum="+startnum+"&obtype="+obtype+"&starttime="+startDate+"&endtime="+endDate
                    +"&stationnum="+stationnum);

            String s = new HttpUtil().doGet("http://58.217.204.132:8001/correctForecast/rain_eval?micapsziplist="+micapsziplistL+
                    "&obfilepath="+obfilepathL+"&startnum="+startnum+"&obtype="+obtype+"&starttime="+startDate+"&endtime="+endDate
                    +"&stationnum="+stationnum);

            return  new ReturnData(ReturnStateCode.SUCCEE.getCode(),ReturnStateCode.SUCCEE.getMsg(),s);
            }
    }

    public String checkouMethod(String method){
        String methodc="";
        //检验方法 0代表TS评分 1代表ETS 2代表空报 3代表漏报 4代表预报偏差 5代表命中率
        switch (method){
            case "0":
                methodc="TS";
                break;
            case "1":
                methodc="ETS";
                break;
            case "2":
                methodc="空报";
                break;
            case "3":
                methodc="漏报";
                break;
            case "4":
                methodc="预报偏差";
                break;
            case "5":
                methodc="命中率";
                break;
        }
        return methodc;
    }

    public String pattern(String p){
        String pattern="";
        switch (p){
            case "0":
                pattern="GREPES";
                break;
            case "1":
                pattern="华南模式";
                break;
            case "2":
                pattern="EC模式";
                break;
            case "3":
                pattern="订正模式";
                break;
        }
        return pattern;
    }

    /**
     * @description:   组装文件目录
     * @return:
     * @author: wjd
     * @time: 2022/1/5 15:12
     */
    public  String[] getFilePath(String type,String startDate,String endDate) throws ParseException {

        String onLinePath="";//在线检验文件目录
        if (type.equals("0")){
            onLinePath="/home/MicapsZip/";
        }else {
            onLinePath="/home/";
        }
       List<String> path=new ArrayList<>();

        Date date0 = new SimpleDateFormat("yyyyMMdd").parse(startDate);

        Date date1 = new SimpleDateFormat("yyyyMMdd").parse(endDate);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Calendar cal = Calendar.getInstance();

        cal.setTime(date0);
        path.add(onLinePath+startDate.substring(2,8));

        while(cal.getTime().compareTo(date1)<0){
            cal.add(Calendar.DAY_OF_MONTH,1);
            path.add(onLinePath+sdf.format(cal.getTime()).substring(2,8));
        }
        String[] strings = new String[path.size()];
        for (String s : path.toArray(strings)) {
            System.out.println(s);
        }
        return  path.toArray(strings);
    }
    @GetMapping(value = "downloadXlsWright" ,produces = MediaType.APPLICATION_OCTET_STREAM_VALUE )
    public void downloadXlsWright(HttpServletResponse response) throws UnsupportedEncodingException {
        // 设置当前的xlsx最大长度为1000行
        SXSSFWorkbook wb = new SXSSFWorkbook(1000);
        // 设置文件后缀
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String fn = "xlsx" + sdf.format(new Date()).toString() + ".xlsx";
        //设置表格名称
        SXSSFSheet sheet = wb.createSheet("sheet1");
        // 设置默认的宽度为30个字符
        sheet.setDefaultColumnWidth(30);
        //第一行
        SXSSFRow row = sheet.createRow(1);
        String name[]={""};
        for (int i = 0; i < 10; i++) {
            // 遍历插入表头
            SXSSFCell cell = row.createCell(0);
            cell.setCellValue("测试表头" + i);
        }
        SXSSFRow row1 = sheet.createRow(1);
        for (int i = 0; i < 10; i++) {
            // 遍历插入表头
            SXSSFCell cell = row1.createCell(i);
            cell.setCellValue("测试表内容" + i);
        }

        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fn, "UTF-8"));
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            wb.write(os);
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (wb != null) {
                wb.dispose();
            }
            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
